import { Checkbox, Divider, Select, SelectProps } from 'antd';
import { FC } from 'react';

export const SelectAll: FC<SelectProps> = memo((props) => {
  const [selectAll, setSelectAll] = useState(false);

  const valueLength = props.value?.length || 0;
  const optionsLength = props.options?.length || 0;

  useEffect(() => {
    setSelectAll(valueLength === optionsLength);
  }, [optionsLength, props.options?.length, props.value?.length, valueLength]);

  const indeterminate = valueLength > 0 && valueLength < optionsLength;

  return (
    <Select
      dropdownRender={(menu) => {
        return (
          <div className="py-8">
            <Checkbox
              className="ml-4"
              checked={selectAll}
              indeterminate={indeterminate}
              onChange={(e) => {
                const allValue = props.options?.map((item) => item.value);
                if (e.target.checked) {
                  props.onChange?.(allValue, []);
                } else {
                  props.onChange?.([], []);
                }
                setSelectAll(e.target.checked);
              }}>
              全选
            </Checkbox>
            <Divider className="mt-8 mb-4" />
            {menu}
          </div>
        );
      }}
      {...props}
      mode="multiple"
      onChange={(value, opts) => {
        setSelectAll(value.length === optionsLength);
        props.onChange?.(value, opts);
      }}
    />
  );
});
